// mongoose setup
require( '../../../config' );
var sinon   = require('sinon'),
    sinonSandbox,
    nock        = require('nock'),
    Promise  = require('promise'),
    assert = require('assert'),
    util = require('../../../../app/components/backend/util'),
    dao = require('../../../../app/components/backend/db'),
    qrcode = require('../../../../app/components/backend/service/qrcode'),
    mockQrFromWeixin = {
      "ticket": "gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm3sUw==",
      "expire_seconds": 60,
      "url": "http:\/\/weixin.qq.com\/q\/kZgfwMTm72WWPkovabbI"
    },
    mockAccessToken = {
      access_token: 'AbCDefGHijKLM_7uxOjq7E7LgTeCPBw-FQa_-NVUviAMjMSKFD-85Z7rfrJa9vLX4-g3IpDJeKh6EpAp231gofjGokYc23nC9oQ4FX_k2Cs',
      create_time: 1449099999999
    },
    mockAccessTokenP = Promise.resolve(mockAccessToken),
    mockUserInfo = {
      "subscribe"     : 1,
      "openid"        : "oNaHXsspWthiBKBda-E5C_OBP_ao",
      "nickname"      : "曾健",
      "sex"           : 1,
      "language"      : "zh_CN",
      "city"          : "大连",
      "province"      : "辽宁",
      "country"       : "中国",
      "headimgurl"    : "http:\/\/wx.qlogo.cn\/mmopen\/7y4xnsv09YZOoic8yb10tqx5rnflfUEFFbMD44F8yqGrDIcAutL4hucrDLeXCN98QQFPkyuNWgj4CpYMMwsygMnJDuplOjF5u\/0",
      "subscribe_time": 1445847409,
      "remark"        : "",
      "groupid"       : 0,
      "promotion_code": util.generatePromotionCode('oNaHXsspWthiBKBda-E5C_OBP_ao')
    },
    mockUserInfoP = Promise.resolve(mockUserInfo),
    mockGetQrTicketFromWeixin = function() {
      return new Promise(function(resolve, reject) {

        // 模拟请求, nock会把执行过的interceptor从list中remove掉; 所以对于一个url的多次请求要多次设置
        nock('https://api.weixin.qq.com').post('/cgi-bin/qrcode/create?access_token=' + mockAccessToken.access_token, {
          "expire_seconds": 604800,
          "action_name": "QR_SCENE",
          "action_info": {
            "scene": {
              "scene_id": + util.generatePromotionCode(mockUserInfo.openid)
            }
          }
        }).reply(200, mockQrFromWeixin);
        resolve();
      });
    };
describe('app/components/backend/service/qrcode', function () {
  describe('#getQrcode()', function () {

    // 测试前置处理
    beforeEach(function () {
      return mockGetQrTicketFromWeixin(true).then(function() {
        // 初始化sinon
        sinonSandbox = sinon.sandbox.create();
        return Promise.resolve();
      });
    });

    // 测试后置处理
    afterEach(function() {

      // 复位
      if (sinonSandbox) sinonSandbox.restore();
    });
    it('[qrcode.Nor.01].获取用户的二维码', function () {

      sinonSandbox.stub(util.weixin, "getAccessToken").returns(mockAccessTokenP);
      sinonSandbox.stub(dao.weixinuser, "findByOpenId").returns(mockUserInfoP);
      return qrcode.getQrcode(mockUserInfo).then(function (url) {
        assert.equal('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + mockQrFromWeixin.ticket, url);
        return Promise.resolve();
      });
    });

    it('[qrcode.Nor.02]. 用户已经有二维码', function () {

      mockUserInfo.qrcode = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFi7zoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2hVaWVlNUhtU1BZeEdNb3RvR2JQAAIEW0VFVgMEgDoJAA=='
      sinonSandbox.stub(util.weixin, "getAccessToken").returns(mockAccessTokenP);
      sinonSandbox.stub(dao.weixinuser, "findByOpenId").returns(Promise.resolve(mockUserInfo));
      return qrcode.getQrcode(mockUserInfo).then(function (url) {
        assert.equal(mockUserInfo.qrcode, url);
        mockUserInfo.qrcode = '';
        return Promise.resolve();
      });
    });
  });
});